#!/usr/bin/env node

const { spawn } = require('child_process');
const path = require('path');
const fs = require('fs');

// 颜色输出
const colors = {
    reset: '\x1b[0m',
    bright: '\x1b[1m',
    red: '\x1b[31m',
    green: '\x1b[32m',
    yellow: '\x1b[33m',
    blue: '\x1b[34m',
    magenta: '\x1b[35m',
    cyan: '\x1b[36m'
};

function log(message, color = 'reset') {
    console.log(`${colors[color]}${message}${colors.reset}`);
}

function logBanner() {
    log(`
${colors.cyan}╔══════════════════════════════════════════════════════════════╗
║                    🐟 闲鱼API服务启动器 🐟                    ║
║                                                              ║
║                XianYuApis - Node.js版本                      ║
║                                                              ║
║                高性能 • 易维护 • 现代化                        ║
╚══════════════════════════════════════════════════════════════╝${colors.reset}
`, 'bright');
}

function checkNodeVersion() {
    const version = process.version;
    const major = parseInt(version.slice(1).split('.')[0]);
    
    if (major < 18) {
        log(`❌ 错误: 需要Node.js 18+版本，当前版本: ${version}`, 'red');
        log('请升级Node.js版本后重试', 'yellow');
        process.exit(1);
    }
    
    log(`✅ Node.js版本检查通过: ${version}`, 'green');
}

function checkDependencies() {
    const packagePath = path.join(process.cwd(), 'package.json');
    
    if (!fs.existsSync(packagePath)) {
        log('❌ 错误: 未找到package.json文件', 'red');
        log('请确保在项目根目录下运行此脚本', 'yellow');
        process.exit(1);
    }
    
    const nodeModulesPath = path.join(process.cwd(), 'node_modules');
    if (!fs.existsSync(nodeModulesPath)) {
        log('⚠️  警告: 未找到node_modules目录', 'yellow');
        log('正在安装依赖...', 'cyan');
        
        return installDependencies();
    }
    
    log('✅ 依赖检查通过', 'green');
    return Promise.resolve();
}

function installDependencies() {
    return new Promise((resolve, reject) => {
        log('📦 正在安装依赖...', 'cyan');
        
        const npm = spawn('npm', ['install'], {
            stdio: 'inherit',
            shell: true
        });
        
        npm.on('close', (code) => {
            if (code === 0) {
                log('✅ 依赖安装完成', 'green');
                resolve();
            } else {
                log('❌ 依赖安装失败', 'red');
                reject(new Error(`npm install failed with code ${code}`));
            }
        });
        
        npm.on('error', (error) => {
            log(`❌ 启动npm失败: ${error.message}`, 'red');
            reject(error);
        });
    });
}

function startServer() {
    log('🚀 正在启动闲鱼API服务器...', 'cyan');
    
    const server = spawn('node', ['src/index.js'], {
        stdio: 'inherit',
        shell: true
    });
    
    server.on('close', (code) => {
        if (code === 0) {
            log('✅ 服务器正常关闭', 'green');
        } else {
            log(`⚠️  服务器异常退出，退出码: ${code}`, 'yellow');
        }
    });
    
    server.on('error', (error) => {
        log(`❌ 启动服务器失败: ${error.message}`, 'red');
    });
    
    // 处理进程信号
    process.on('SIGINT', () => {
        log('\n🛑 收到中断信号，正在关闭服务器...', 'yellow');
        server.kill('SIGINT');
        process.exit(0);
    });
    
    process.on('SIGTERM', () => {
        log('\n🛑 收到终止信号，正在关闭服务器...', 'yellow');
        server.kill('SIGTERM');
        process.exit(0);
    });
    
    return server;
}

async function main() {
    try {
        logBanner();
        
        // 检查Node.js版本
        checkNodeVersion();
        
        // 检查依赖
        await checkDependencies();
        
        // 启动服务器
        startServer();
        
    } catch (error) {
        log(`❌ 启动失败: ${error.message}`, 'red');
        process.exit(1);
    }
}

// 如果直接运行此脚本
if (require.main === module) {
    main();
}

module.exports = { main, checkNodeVersion, checkDependencies, startServer };
